import React from 'react';
import PropTypes from 'prop-types';
import { observer } from 'mobx-react';
import LazilyLoad, { importLazy } from 'components/lazilyLoad';
import prepareModule from 'components/hoc/prepareModule';
import prepareThumbModule from 'components/hoc/prepareThumbModule';
import css from './index.less';

let modules = {};

@observer
export default class FrameContentRender extends React.Component {

  static propTypes = {
    frame: PropTypes.object,
    maxWidth: PropTypes.number,
    isThumb: PropTypes.bool,
    isPreview: PropTypes.bool,
    current: PropTypes.object,
    previewMotion: PropTypes.object,
  };

  static defaultProps = {
    frame: { list: [] },
    maxWidth: 375,
    isThumb: false, // 是否是帧的缩略图
    isPreview: false, // 是否是预览模式
    current: {},
    previewMotion: {},
  };

  constructor() {
    super();
  }

  render() {
    const { frame, isThumb, maxWidth, isInitial, topPosition} = this.props;
    const { list } = frame;
    const scale = maxWidth / 750;

    list.forEach((_mod) => {
      if (!modules[_mod.type]) {
        modules[_mod.type] = () => importLazy(import(`components/motionsRender/modules/${_mod.type}/render`));
      }
    });
    const props = {
      modules: {
        ...modules // 注意，这里必须要解构赋值
      },
    };
    return (
      <LazilyLoad {...props}>
        {
          ({...components}) => (
            <div style={{
              height: `${frame.height * scale}px`,
              width: `${maxWidth}px`,
            }}>
              <div
                className={css.frameContent}
                style={{
                  height: `${frame.height}px`,
                  transform: `scale(${scale})`,
                  transformOrigin: '0 0',
                }}
              >
                {
                  list.map((frameEle, index) => {
                    const { type } = frameEle;
                    if (components[type]) {
                      // isBelongInitial是否属于初始帧，初始帧不能编辑
                      if (!isThumb) frameEle.isBelongInitial = isInitial;
                      const C = isThumb ? prepareThumbModule(components[type], frameEle) : prepareModule(components[type], frameEle);
                      return <C key={index} mod={frameEle} topPosition={topPosition}/>;
                    }
                  })
                }
              </div>
            </div>

          )
        }
      </LazilyLoad>
    );
  }
}
